package com.linxz.framework.protocol.retrofit;

import com.linxz.framework.configuration.ConfigKeys;
import com.linxz.framework.configuration.Linxz;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import javax.net.ssl.*;
/**
 * @author Linxz
 * 创建日期：2019年02月20日 20:11
 * version：1.0.0
 * 描述：
 */
public class LinxzHttpCreator {
    /**
     * 构建Http
     * */
    private static final class OkHttpHolder {
        private static final int TIME_OUT = 60;
        private static final OkHttpClient.Builder BUILDER = new OkHttpClient.Builder();
        private static final ArrayList<Interceptor> INTERCEPTORS = Linxz.getConfiguration(ConfigKeys.INTERCEPTOR);
        private static OkHttpClient.Builder addInterceptor() {
            if (INTERCEPTORS != null && !INTERCEPTORS.isEmpty()) {
                for (Interceptor interceptor : INTERCEPTORS) {
                    BUILDER.addInterceptor(interceptor);
                }
            }
            return BUILDER;
        }

        /**
         * http请求
         * */
        private static final OkHttpClient OK_HTTP_CLIENT = addInterceptor()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();


        /**
         * https请求
         * */
        private static final OkHttpClient OK_HTTPS_CLIENT = httpsBuilder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();


        private static OkHttpClient.Builder httpsBuilder(){
            try {
                TrustManager[] trustAllCerts = buildTrustManagers();
                final SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

                final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                OkHttpClient.Builder builder =addInterceptor();

                builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
                builder.hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
                return builder;
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                e.printStackTrace();
                return new OkHttpClient.Builder();
            }
        }

        private static TrustManager[] buildTrustManagers() {
            return new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };
        }
    }

    /**
     * 构建全局Retrofit客户端
     */
    private static final class RetrofitHolder {
        private static final Retrofit RETROFIT_CLIENT = new Retrofit.Builder()
                .baseUrl(Linxz.getConfiguration(ConfigKeys.API_HOST).toString())
                .client(OkHttpHolder.OK_HTTP_CLIENT)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    private static final class HttpStoreHolder {
        private static final HttpStore REST_SERVICE = RetrofitHolder.RETROFIT_CLIENT.create(HttpStore.class);
    }

    public static HttpStore getDefaultHttpStore(){
        return HttpStoreHolder.REST_SERVICE;
    }

    public static HttpStore getHttpStore(){
        return HttpStoreHolder.REST_SERVICE;
    }

    public static OkHttpClient getHttpsClent(){
        return OkHttpHolder.OK_HTTPS_CLIENT;
    }


    /**外部提供的apiStore*/
    public static <T> T getOutApiStore(final Class<T> service){
        return RetrofitHolder.RETROFIT_CLIENT.create(service);
    }

}
